package com.mikewoo.nio;

import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;

/**
 * Title: ClientThread.java
 * Description:  SelectorSocketChannel Client轮询工作线程
 * 
 * author     Phantom
 * date       2016年5月20日 上午10:58:49
 * @version    1.0.0
 */
public class ClientThread extends Thread {

	private Selector selector;
	
	
	public ClientThread(Selector selector) {
		super();
		this.selector = selector;
	}


	@Override
	public void run() {
		try {
			while (selector.select() > 0) {
				for (SelectionKey key : selector.selectedKeys()) {
					SocketChannel socketChannel = (SocketChannel) key.channel();
					ByteBuffer byteBuffer = ByteBuffer.allocate(48);
					int size = socketChannel.read(byteBuffer);
					while (size > 0) {
						byteBuffer.flip();
						Charset charset = Charset.forName("UTF-8");
						System.out.println(charset.newDecoder().decode(byteBuffer).toString());
						size = socketChannel.read(byteBuffer);
					}
					selector.selectedKeys().remove(key);
				}
			}
		} catch(Exception e) {
			e.printStackTrace();
		}
	}

	
}
